﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

using AForge;
using AForge.Video;
using AForge.Video.DirectShow;
using AForge.Vision.Motion;
using System.Drawing.Imaging;
using AForge.Imaging;

namespace MotionDetect
{
    public partial class Form1 : Form
    {
        private IVideoSource videoSource = null;
        // motion detector
        MotionDetector detector = new MotionDetector(
            new TwoFramesDifferenceDetector(),
            new MotionAreaHighlighting());
        private List<float> motionHistory = new List<float>();
        private int detectedObjectsCount = -1;
        // current statistics index
        private int statIndex = 0;
        // ready statistics values
        private int statReady = 0;
        string koordinata = "";
        private int flash = 0;
        private float motionAlarmLevel = 0.015f;
        VideoCaptureDevice video;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            video = new VideoCaptureDevice(new FilterInfoCollection(FilterCategory.VideoInputDevice)[0].MonikerString);
            video.DesiredFrameSize = new System.Drawing.Size(160, 120);
            OpenVideoSource(video);
            
            //foreach(Size in videoSource.)
            //felbontásToolStripMenuItem.DropDownItems.Add("izé");
        }

        private void OpenVideoSource(IVideoSource source)
        {
            // set busy cursor
            this.Cursor = Cursors.WaitCursor;

            // close previous video source
            CloseVideoSource();

            // start new video source
            videoSourcePlayer.VideoSource = new AsyncVideoSource(source);
            videoSourcePlayer.Start();

            // reset statistics
            statIndex = statReady = 0;

            // start timers
            timer.Start();
            alarmTimer.Start();

            videoSource = source;

            this.Cursor = Cursors.Default;
        }

        private void CloseVideoSource()
        {
            // set busy cursor
            this.Cursor = Cursors.WaitCursor;

            // stop current video source
            videoSourcePlayer.SignalToStop();

            // wait 2 seconds until camera stops
            for (int i = 0; (i < 50) && (videoSourcePlayer.IsRunning); i++)
            {
                Thread.Sleep(100);
            }
            if (videoSourcePlayer.IsRunning)
                videoSourcePlayer.Stop();

            // stop timers
            timer.Stop();
            alarmTimer.Stop();

            motionHistory.Clear();

            // reset motion detector
            if (detector != null)
                detector.Reset();

            videoSourcePlayer.BorderColor = Color.Black;
            this.Cursor = Cursors.Default;
        }

        int x,y;
        bool t = true;
        private void videoSourcePlayer_NewFrame(object sender, ref Bitmap image)
        {
            lock (this)
            {
                if (!t)
                    ProcessImage(image);
                else
                    MotionDetect(image);


            }
        }



        

        private void MotionDetect(Bitmap image) 
        {
            if (detector != null)
            {
                float motionLevel = detector.ProcessFrame(image);

                if (motionLevel > motionAlarmLevel)
                {
                    // flash for 2 seconds
                    flash = (int)(2 * (1000 / alarmTimer.Interval));
                }

                // check objects' count
                if (detector.MotionProcessingAlgorithm is BlobCountingObjectsProcessing)
                {
                    BlobCountingObjectsProcessing countingDetector = (BlobCountingObjectsProcessing)detector.MotionProcessingAlgorithm;
                    detectedObjectsCount = countingDetector.ObjectsCount;
                }
                else
                {
                    detectedObjectsCount = -1;
                }

                // accumulate history
                motionHistory.Add(motionLevel);
                if (motionHistory.Count > 300)
                {
                    motionHistory.RemoveAt(0);
                }
            }
        }
        
        

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseVideoSource();
        }

        private void videoSourcePlayer_MouseClick(object sender, MouseEventArgs e)
        {
            int x=(int)((e.X/640.0)*160.0);
            int y = (int)((e.Y / 480.0) * 120.0);
            label3.Text = videoSourcePlayer.GetCurrentVideoFrame().Size.ToString()+"{"+x+", "+y+",}";
            Href = videoSourcePlayer.GetCurrentVideoFrame().GetPixel(x,y ).GetHue();
            Sref = videoSourcePlayer.GetCurrentVideoFrame().GetPixel(x, y).GetSaturation();
            t = false;
            Text = Href+", "+Sref;
            showMotion.Stop();
            showMotion.Start();
            //label1.Text = videoSourcePlayer.GetCurrentVideoFrame().Width+"";
        }

        private void showMotion_Tick(object sender, EventArgs e)
        {
            string kiir="";
            if (X != 0 & Y != 0 & talalatok>200)
            {
                    if (X < 80 & Y < 60)
                    {
                        if (game != null)
                        game.ugorjon = true;
                        kiir += "balfelső";
                    }
                    else if (X > 80 & Y < 60)
                    {
                        if (game != null)
                        game.ugorjon1 = true;
                        kiir += "jobbfelső";
                    }

            }
            else kiir = "semmi";

            label2.Text = talalatok+","+kiir;
        }

        private void felbontásToolStripMenuItem_Click(object sender, EventArgs e)
        {
            video.DisplayPropertyPage(this.Handle);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread thread = new Thread(() =>
            {
                game = new KillerIndex.Game1();
                game.Run();
            });
            thread.Start();
            
           
        }
        KillerIndex.Game1 game;
        private void button2_Click(object sender, EventArgs e)
        {
            game.ugorjon = true;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            game.ugorjon1 = true;
        }
    }
}
